<template>
<div>
  <div class="top">
  <van-search
    v-model="value"
    show-action
    placeholder="请输入搜索关键词"
    autofocus
    shape="round"
    @search="onSearch"
    @cancel="cancel"
  >
  </van-search>
  </div>
   <div class="history">
    <div class="tit">
     <div>搜索记录</div>
     <div @click="del" class="del">
      <van-icon name="delete" size="30px" />
     </div>
    </div>
    <div v-if="historyList.length > 0">
      <span class="his_list"  v-for="(item,i) in historyList" :key="i" @click="keySearch(item)">{{item}}</span>
    </div>
    <div v-else class="noHis">
    暂无历史记录
    </div>
   </div>
   </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { Dialog,Toast } from 'vant';
export default { 
  name:"search",
  data()
  {
    return{
        value:"",
        historyList:[]
    }
  },
  methods: {
   ...mapActions(["setSerchKey"]),
   onSearch()
    {
      let {value,historyPush,setSerchKey} = this;
      if(value.trim() === "")
      {
        Toast("请输入内容再进行检索")
        return
      }
       setSerchKey(value).then(()=>{
        historyPush(value);
        this.$router.push({
          path:"/list"
        });
      });   
  },
  //删除历史记录
   del()
   { 
   let that = this
   if(that.historyList.length == 0) return;
    Dialog.confirm({
        title: "标题",
        message: "确定清空历史记录?"
      }).then(() => {
        that.historyList = [];
        window.localStorage.setItem("historyArr", JSON.stringify([]));
      });
   },
   //新增加历史记录
   historyPush(key){
    if(key == "") return;
    let arr = JSON.parse(window.localStorage.getItem("historyArr"))
    if(arr && typeof arr === "object")
    {
     
      if(arr.indexOf(key) < 0)
      {
        arr.push(key)
        window.localStorage.setItem("historyArr", JSON.stringify(arr));
      }
    }else
    {
      let array = []
      array.push(key)
       window.localStorage.setItem("historyArr", JSON.stringify(array));
    }
  },
    keySearch(key){
      let {setSerchKey} = this
       setSerchKey(key).then(() => {
        this.$router.push({
          path: "/list"
        });
      });
    },
  init()
  {
     let arr = JSON.parse(window.localStorage.getItem("historyArr"))
     if(arr)
     {
      this.historyList = arr
     }
  },
  cancel()
  {
    this.$router.push({
       path:"/"
    })
  }
},
computed:{
  ...mapState(["serchKey"])
},
created()
{
   this.init()
}
}
</script>

<style lang="less" scoped>
.histroy
{
  margin-top: 60px;
  padding: 0 10px;
}
.tit
{
  padding: 20px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
}
.his_list
{
  background: #f3eeee;
  color: #505050;
  padding: 10px 5px;
  border-radius: 5px;
  display: line-block;
  margin-top: 10px;
  margin-left: 20px;
}
.del{
  position: absolute;
  right: 100px;
  top: 50px;
}
</style>